/*
 * Nota.java
 *
 * Created on 02/07/2007, 10:32:59
 *
 */
package br.com.grillo.jturbonote;

import java.awt.Rectangle;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.net.InetAddress;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import static br.com.grillo.jturbonote.Main.*;

import static br.com.grillo.jturbonote.GerenciadorNotas.*;

/**
 *
 * @author grillo
 */
public class Nota implements Serializable {

    private byte[] input;
    private List<String> lines = new ArrayList<String>();
    private Properties attrs = new Properties();
    static final String LINE_END = "#\r\n";
    private InetAddress source;
    private Long date;
    private String message;
    private int lineFile;
    private int tamFile;

    public Nota() {
    }

    public Nota(byte[] input, InetAddress source) {
        this.input = input;
        setText();
        setDate(System.currentTimeMillis());
        setSource(source);
        checkAttach();
    }

    public InetAddress getSource() {
        return source;
    }

    public void checkAttach() {

        String nomeArquivo = "temp.bin"; //getTexto().indexOf("ATTACHED");

        int lastEnd = -1;
        int qtdN = 0;
        for (int i = 0; i < input.length; i++) {
            if (input[i] == '\n') {
                qtdN++;
                if (qtdN == lineFile) {
                    lastEnd = i;
                    break;
                }
            }
        }
        if (lastEnd > 0) {
            File attach = new File(getInstance().getDiretorioArquivos(), nomeArquivo);

            try {
                FileUtils.writeByteArrayToFile(attach, Arrays.copyOfRange(input, lastEnd, input.length));
                //System.out.println("FILE {" + IOUtils.toString(bout.toByteArray(), "ISO-8859-1") + "\n");
            } catch (IOException ioEx) {
                logger.severe("Erro ao criar anexo " + ioEx.getMessage());
            }
        }
    }

    private void setSource(InetAddress source) {
        this.source = source;
    }

    public Rectangle getBounds() {
        Rectangle saida = new Rectangle();
        saida.setSize(Integer.parseInt(attrs.getProperty("Width")), Integer.parseInt(attrs.getProperty("Height")));
        saida.setLocation(Integer.parseInt(attrs.getProperty("X")), Integer.parseInt(attrs.getProperty("Y")));
        return saida;
    }

    private void setDate(Long date) {
        this.date = date;
    }

    public Long getDate() {
        return date;
    }

    public String getMessage() {
        StringBuilder st = new StringBuilder();
        for (String linha : lines) {
            if (linha.endsWith("End of TCPIP text#")) {
                st.append(linha.substring(0, linha.indexOf("End of TCPIP text#")));
                break;
            } else {
                st.append(linha + "\r\n");
            }
        }
        return st.toString();
    }

    public byte[] getInput() {
        return input;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @SuppressWarnings(value = "unchecked")
    public void setText() {
        try {
            String text = IOUtils.toString(input, "ISO-8859-1");
            if (text != null) {
                StringReader sr = new StringReader(text);
                lines = IOUtils.readLines(sr);
                sr.close();
                parseProperties();
            }
        } catch (IOException ioEx) {
            logger.log(Level.SEVERE, "Erro ao montar nota", ioEx);
        }

    }

    private void parseProperties() throws IOException {
        StringBuilder temp = new StringBuilder();
        int i = 0;
        for (String line : lines) {
            i++;

            if (line.indexOf("=") > 0 && (line + "\r\n").indexOf(LINE_END) > 0) {
                temp.append(line.substring(0, line.length() - 1) + "\r\n");
            }
            if (line.startsWith("Attachment follows")) {
                tamFile = Integer.parseInt(line.split(",")[1]);
                lineFile = ++i;
            }
        }
        attrs.load(new StringReader(temp.toString()));
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        s.append(getDataFormatada(getDate()) + " - ");
        s.append("De " + attrs.getProperty("From"));
        s.append(" em " + attrs.getProperty("SentBy"));
        String title = attrs.getProperty("SZTITLE");
        if (!title.trim().equals("")) {
            s.append(" - " + title);
        }
        return s.toString();
    }

    public String getAttrs(String key) {
        return attrs.getProperty(key);
    }

    public String toTurboNote() {
        StringBuilder s = new StringBuilder();
        s.append(message);
        s.append("End of TCPIP text" + LINE_END);
        s.append("From=" + System.getProperty("user.name") + LINE_END);
        //attrs.setProperty("SENDERCODE", "lEYmIl6mo8:;w`3u/tCl]MxC`p^jDSTlAHS=m]vMp[a4DO4mtutO");
        try {
            s.append("SentBy=" + InetAddress.getLocalHost().getCanonicalHostName() + LINE_END);
        } catch (IOException ioEx) {
        }
        if (attrs.contains("StayOnTop")) {
            s.append("StayOnTop=" + attrs.getProperty("StayOnTop") + LINE_END);
        } else {
            s.append("StayOnTop=" + LINE_END);
        }
        s.append("X=" + attrs.getProperty("X") + LINE_END);
        s.append("Y=" + attrs.getProperty("Y") + LINE_END);

        s.append("Width=" + attrs.getProperty("Width") + LINE_END);
        s.append("Height=" + attrs.getProperty("Height") + LINE_END);
        s.append("SZTITLE=" + attrs.getProperty("SZTITLE") + LINE_END);
        /*
        attrs.setProperty("HasBorder", "");
        attrs.setProperty("BkColor", "");
        attrs.setProperty("FoColor", "16777215");
        attrs.setProperty("TiBkColor", "0");
        attrs.setProperty("TiFoColor", "16777215");
        attrs.setProperty("Sponsored", "");
        attrs.setProperty("LFHEIGHT", "-13");
        attrs.setProperty("LFWIDTH", "0");
        attrs.setProperty("LFESCAPEME", "0");
        attrs.setProperty("LFORIENTAT", "0");
        attrs.setProperty("LFWEIGHT", "400");
        attrs.setProperty("LFITALIC", "0");
        attrs.setProperty("LFUNDERLIN", "0");
        attrs.setProperty("LFSTRIKEOU", "0");
        attrs.setProperty("LFCHARSET", "0");
        attrs.setProperty("LFOUTPRECI", "3");
        attrs.setProperty("LFCLIPPREC", "2");
        attrs.setProperty("LFQUALITY", "1");
        attrs.setProperty("LFPITCHAND", "34");
        attrs.setProperty("LFFACENAME", "Trebuchet MS");
        attrs.setProperty("LFHEIGHTTI", "-13");
        attrs.setProperty("LFWIDTHTI", "0");
        attrs.setProperty("LFESCAPETI", "0");
        attrs.setProperty("LFORIENTTI", "0");
        attrs.setProperty("LFWEIGHTTI", "700");
        attrs.setProperty("LFITALICTI", "0");
        attrs.setProperty("LFUNDERLTI", "0");
        attrs.setProperty("LFSTRIKETI", "0");
        attrs.setProperty("LFCHARSETI", "0");
        attrs.setProperty("LFOUTPRETI", "3");
        attrs.setProperty("LFCLIPPRTI", "2");
        attrs.setProperty("LFQUALITTI", "1");
        attrs.setProperty("LFPITCHTI", "34");
        attrs.setProperty("LFFACENATI", "Trebuchet MS");
        attrs.setProperty("SZATTACHEDFILE", "");
        attrs.setProperty("ALARMTIME", "");
        attrs.setProperty("RECURRINGALARMTYPE", "");
        attrs.setProperty("RECURRINGALARMVALUE", "");
        attrs.setProperty("ORIGINALDEST", "");
        attrs.setProperty("AUTOREGISTER", "");
        attrs.setProperty("INSERTSENTTOLIST", "");
        attrs.setProperty("ROLLUP", "");

        for (Object key : attrs.keySet()) {

        s.append(key.toString() + "=");
        s.append(attrs.getProperty((String) key));
        s.append(LINE_END);
        }*/

        return s.toString();
    }

    public void setBounds(Rectangle bounds) {
        attrs.setProperty("Width", String.valueOf((int) bounds.getWidth()));
        attrs.setProperty("Height", String.valueOf((int) bounds.getHeight()));
        attrs.setProperty("X", String.valueOf((int) bounds.getX()));
        attrs.setProperty("Y", String.valueOf((int) bounds.getY()));
    }

    public void setProperty(String key, String value) {
        attrs.setProperty(key, value);
    }
}
